﻿// Project:		Guan.CMS.Domain - Guan.Cms
// FileName:	AddOrUpdateProductHandler.cs
// 
// Author:		Cooclsee
// Email:		cooclsee@qq.com
// Created:		2013-03-12 20:43
// Modified:	2013-03-11 23:46

using System;
using System.Web;
using Guan.CMS.CommandProcessor.Command;
using Guan.CMS.Data.Infrastructure;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Commands.Product;

namespace Guan.CMS.Domain.Handlers.Product
{
    public class AddOrUpdateProductHandler : ICommandHandler<AddOrUpdateProductCommand>
    {
        private readonly IProductRepository _productRepository;
        private readonly IUnitOfWork _unitOfWork;

        public AddOrUpdateProductHandler(IProductRepository productRepository,IUnitOfWork unitOfWork)
        {
            this._productRepository = productRepository;
            this._unitOfWork = unitOfWork;
        }

        public ICommandResult Execute(AddOrUpdateProductCommand command)
        {
            var isAdd = command.Id == 0;
            var now = DateTime.Now;
            Model.Entities.Product product = null;
            if (!isAdd)
            {
                product = _productRepository.GetById(command.Id);
            }
            else
            {
                product = new Model.Entities.Product
                              {
                                  CreatedTime = now
                              };
            }
            product.Name = command.Name;
            product.ShortDescription = command.ShortDescription;
            product.FullDescription = HttpUtility.HtmlDecode(command.FullDescription);
            product.IsPublished = command.IsPublished;
            product.IsRecommend = command.IsRecommend;
            product.UpdatedTime = now;
            product.CategoryId = command.CategoryId;
            product.MetaKeywords = command.MetaKeywords;
            product.MetaDescription = command.MetaDescription;
            product.MetaTitle = command.MetaTitle;
            product.FriendlyName = command.FriendlyName;
            if (isAdd)
            {
                _productRepository.Add(product);
            }
            else
            {
                _productRepository.Update(product);
            }
            _unitOfWork.Commit();
            return new CommandResult(true,product.Id);
        }
    }
}